package itpenguin.review;

import itpenguin.common.PMFactory;
import itpenguin.review.entities.Item;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class ArchiveListServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String pathinfo = req.getPathInfo();
		String[] info = req.getPathInfo().split("/");

		if (pathinfo == null) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		if (info.length != 3)
			throw new ServletException();

		short year;
		short month;
		try {
			year = Short.parseShort(info[1]);
			month = Short.parseShort(info[2]);
		} catch (NumberFormatException e) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("JST"));
		cal.set(year, month - 1, 1, 0, 0, 0);
		Date beginDate = cal.getTime();
		cal.add(Calendar.MONTH, 1);
		Date endDate = cal.getTime();
		
		PersistenceManager pm = null;
		Collection<Item> items = null;
		try {
			pm = PMFactory.getInstance().getPersistenceManager();
			Query query = pm.newQuery("select from itpenguin.review.entities.Item "
					+ "where reviewDate >= beginDateParam "
					+ "&& reviewDate < endDateParam "
					+ "parameters java.util.Date beginDateParam, "
					+ "java.util.Date endDateParam "
					+ "order by reviewDate desc");
			items = (Collection<Item>) query.execute(beginDate, endDate);
			items = pm.detachCopyAll(items);

		} finally {
			pm.close();
		}
		
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(Item item : items) {
			Map<String, Object> review = new HashMap<String, Object>();
			review.put("itemId", item.getItemId());
			review.put("title", item.getReviewTitle());
			review.put("date", item.getReviewDate());
			review.put("score", item.getScore());
			list.add(review);
		}
		
		Gson gson = new Gson();
		String json = gson.toJson(list);
		
		resp.setContentType("application/json");
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().println(json);
	}


}
